using Microsoft.AspNetCore.Mvc;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.QualityCommand;
using RBAC.Read.Api.Application.Dto.Quality;
using System.Text;

namespace RBAC.Read.Api.Controllers.QualityManage
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    /// <summary>
    /// 质量工单 读端控制器。
    /// </summary>
    /// <remarks>
    /// - 提供质量工单的分页、详情与附件列表查询。
    /// - 通过 MediatR 将请求分发至对应处理器，控制器不承载业务逻辑。
    /// </remarks>
    public class QualityOrderController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<QualityOrderController> _logger;

        public QualityOrderController(IMediator mediator, ILogger<QualityOrderController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取质量工单分页（无筛选条件）。
        /// </summary>
        /// <remarks>
        /// 查询参数：<see cref="GetQualityOrderListCommand"/>。
        /// 返回：<see cref="APIPaging{T}"/> 包装的 <see cref="QualityOrderListItemDto"/> 集合。
        /// 示例：GET api/QualityOrder/GetQualityOrderList?pageIndex=1&pageSize=10
        /// </remarks>
        [HttpGet]
        public Task<APIPaging<QualityOrderListItemDto>> GetQualityOrderList([FromQuery] GetQualityOrderListCommand request, CancellationToken cancellationToken)
        {
            // 通过 MediatR 分发至分页查询处理器
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取质量工单详情（按 Id）。
        /// </summary>
        /// <remarks>
        /// 路由参数：工单 Id。
        /// 返回：<see cref="QualityOrderDetailDto"/>。
        /// 示例：GET api/QualityOrder/GetQualityOrderDetailById/123
        /// </remarks>
        [HttpGet("{id:long}")]
        public Task<APIResult<QualityOrderDetailDto>> GetQualityOrderDetailById([FromRoute] long id, CancellationToken cancellationToken)
        {
            // 组装查询命令并通过 MediatR 分发
            var request = new GetQualityOrderDetailByIdCommand { Id = id };
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 按质量工单 Id 获取附件列表。
        /// </summary>
        /// <remarks>
        /// 路由参数：工单 Id。
        /// 返回：<see cref="APIResult{T}"/> 包装的 <see cref="List{T}"/>，元素为 <see cref="QualityOrderAttachmentDto"/>。
        /// 示例：GET api/QualityOrder/GetQualityOrderAttachmentListByOrderId/123
        /// </remarks>
        [HttpGet("{orderId:long}")]
        public Task<APIResult<List<QualityOrderAttachmentDto>>> GetQualityOrderAttachmentListByOrderId([FromRoute] long orderId, CancellationToken cancellationToken)
        {
            // 组装查询命令并通过 MediatR 分发
            var request = new GetQualityOrderAttachmentListByOrderIdCommand { OrderId = orderId };
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 导出质量工单为 .xlsx 文件。
        /// </summary>
        /// <remarks>
        /// 参数与分页查询保持一致：
        /// - pageIndex：页码，从 1 开始
        /// - pageSize：每页大小
        /// - orderBy：排序（示例："Id DESC"）
        /// 示例：GET api/QualityOrder/ExportQualityOrders?pageIndex=1&pageSize=100&orderBy=Id%20DESC
        /// </remarks>
        [HttpGet]
        public async Task<IActionResult> ExportQualityOrders([FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 100, [FromQuery] string? orderBy = "Id DESC", CancellationToken cancellationToken = default)
        {
            // 组装导出命令并通过 MediatR 分发
            var cmd = new ExportQualityOrderCommand { PageIndex = pageIndex, PageSize = pageSize, OrderBy = orderBy ?? "Id DESC" };
            var res = await _mediator.Send(cmd, cancellationToken);

            if (res.Code != APIEnums.Success)
            {
                _logger.LogWarning("导出质量工单失败：{Msg}", res.Msg);
                return BadRequest(res.Msg);
            }

            var bytes = res.Data ?? Array.Empty<byte>();
            var fileName = $"产品质检{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            const string mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            return File(bytes, mime, fileName);
        }
    }
}
